import { config } from '../../config.js';
// var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk,_self;
const app = getApp();
var logs = wx.getStorageSync('logs') || []
function logging(message){
  logs.unshift(message);
  wx.setStorageSync('logs', logs);
}

Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    showModel:false,
    shareOptions:null,
    location:""
  },
  agreeGetUser: function(e) {
    app.globalData.userInfo = e.detail.userInfo;
    wx.setStorageSync("userInfo", e.detail.userInfo);

    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true,
      showModel:false
    })
    this.login();
  },
  initUserInfo:function(){
    let _self = this;
    if (app.globalData.userInfo) {
        this.setData({
          userInfo: app.globalData.userInfo,
          hasUserInfo: true
        })
      _self.login();
    } else if (this.data.canIUse) {
        app.userInfoReadyCallback = res => {
          _self.saveUserInfo(res.userInfo);
        }

      wx.getSetting({
        success: res => {
          if (res.authSetting['scope.userInfo'] === true) { // 成功授权
            // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
            wx.getUserInfo({
              success: res => {
                //_self.saveUserInfo(res.userInfo);
                // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                // 所以此处加入 callback 以防止这种情况
                if (app.userInfoReadyCallback) {
                  app.userInfoReadyCallback(res)
                }
              },
              fail: res => {
                console.log(res)
              }
            })
          } else if (res.authSetting['scope.userInfo'] === false) { // 授权弹窗被拒绝
            wx.showModal({
              title: '提示',
              content: '设置内大校友小程序获取您的公开信息(用户名、头像等)',
              success: function (res) {
                if (res.confirm) {
                  wx.openSetting({
                    success: res => {
                    },
                    fail: res => {
                    }
                  })
                }
              }
            })
          } else { // 没有弹出过授权弹窗
            _self.setData({
              showModel: true
            });
          }
        }
      })

    } 


  },
  saveUserInfo:function (userInfo){
    wx.setStorageSync("userInfo", userInfo);
    app.globalData.userInfo = userInfo;
    this.login();
  },
  onLoad: function (options) {
    _self = this;
    // qqmapsdk = new QQMapWX({
    //   key: config.map_key
    // });

    console.log("wxlogin option",JSON.stringify(options));
    if (options.inviteUserId){
      _self.setData({
        shareOptions: options
      })
    }

    wx.setStorageSync("shareOptions", this.data.shareOptions);
    _self.initUserInfo();
  },
  isLogin:function(){
    let header;
    header = {
      'cookie': wx.getStorageSync("sessionid")//读取cookie
    };
    wx.showLoading({
      title: '登录中',
    })
    
    let loginData = {
      "mobileType": app.globalData.deviceInfo,
      "geographicLocation":""
    }
    //wx.setStorageSync("location", loginData)
    wx.request({
      url: config.api_base_url+ '/usr/islogin',
      method:"POST",
      data:loginData,
      header:header,
      success:function(res){
        let errCode = res.data.errCode;
        let errMsg = res.data.errMsg;
        //errCode='0006'
       
        if (errCode == '0000') {
          let data = res.data.data[0];
          wx.setStorageSync("usercache", data);
          logging("登录成功")
          //00 未认证 01申请 02通过 03未通过
          if(data.ischecked=='02'){
            wx.switchTab({
              url: '/pages/index/index'
            });
          }else{
            wx.redirectTo({
              url: "/pages/certification/certification"
            });
          }
       
        //用户手动点击退出
        }else if(errCode=='0004'){
          wx.setStorageSync("sessionid", "");
            wx.redirectTo({
              url: "/pages/login/login"
            });
        }else if(errCode=='0006'){
          //用户没有注册,跳转到注册页面
          logging("用户没有注册,跳转到注册页面")
          wx.redirectTo({
             url: '/pages/register/register'
          })
        }else {
          wx.showToast({
            title: "/usr/islogin"+errCode+errMsg,
            icon: 'none',
            duration: 3000
          }) 
        }
        wx.hideLoading();
      }
    })
  },
  login:function(){
    wx.login({
      success: function (res) {
        if (res.code) {
          //发起网络请求
          wx.showLoading({
            title: '登录中',
          })
          wx.request({
            url: config.api_base_url + '/sys/getwxinfo',
            data: {
              code: res.code
            },
            success: function (res) {
              let errCode = res.data.errCode;
              if (errCode == '0000') {
                let data = res.data.data[0];
                wx.setStorageSync("sessionid", res.header["Set-Cookie"]);
                _self.isLogin();

                // wx.getLocation({
                //   type: 'gcj02',
                //   success: function (res) {
                //     var latitude = res.latitude
                //     var longitude = res.longitude
                //     var location = {
                //       latitude: latitude,
                //       longitude: longitude
                //     }
                //     qqmapsdk.reverseGeocoder({
                //       location: location,
                //       success: function (res) {
                //         console.log(JSON.stringify(res))
                //         _self.setData({
                //           location:res.result.address
                //         })
                //         _self.isLogin();
                //       },
                //       fail: function (err) {
                //         console.log(err)
                //         _self.isLogin();
                //       }
                //     })
                //   }
                // })
               
              } else {
                wx.showToast({
                  title: "服务器出问题啦,退出小程序 再来一次试试",
                  icon: 'none',
                  duration: 3000
                })
              }
              wx.hideLoading();
            },
            fail: function (error) {
              console.log(error);
              wx.hideLoading();
            }
          })
        } else {
          console.log('登录失败！' + res.errMsg);
          wx.hideLoading()
        }
      }
    });
  }
})